﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Tools.Base;

namespace LogicCenter.Threads
{
    public class ThreadManager
    {
        /// <summary>
        /// 后台线程起搏器
        /// </summary>
        static Timer BackThreadDriver = null;

        /// <summary>
        /// LOG线程
        /// </summary>
        static BackgroundWorker LogFileWorker = null;

        /// <summary>
        /// 主逻辑线程
        /// </summary>
        static BackgroundWorker MainLogicWorker = null;

        /// <summary>
        /// 主逻辑的辅助线程（分发事件）线程
        /// </summary>
        static BackgroundWorker MainDispatcherWorker = null;

        static public void Init()
        {
            // 后台线程起搏器初始化
            BackThreadDriver = new Timer(BackThreadDriverFunc, null, 1000, 999);

            // Log线程初始化
            LogFileWorker = new BackgroundWorker();
            LogFileWorker.DoWork += LogManager.ThreadFunc;

            // 主逻辑线程初始化
            MainLogicWorker = new BackgroundWorker();
            MainLogicThread.Instance().SetMyWorker(MainLogicWorker);
            MainLogicWorker.DoWork += MainLogicThread.Instance().ThreadFunc;

            // 主逻辑的辅助线程（分发事件）初始化
            MainDispatcherWorker = new BackgroundWorker();
            MainDispatcherThread.Instance().SetMyWorker(MainDispatcherWorker);
            MainDispatcherWorker.DoWork += MainDispatcherThread.Instance().ThreadFunc;
        }

        /// <summary>
        /// 停止后台线程起搏器
        /// </summary>
        static public void StopBackThreadDriver()
        {
            BackThreadDriver.Change(Timeout.Infinite, Timeout.Infinite);
        }

        static void BackThreadDriverFunc(Object sender)
        {
            if (LogFileWorker != null && !LogFileWorker.IsBusy)
                LogFileWorker.RunWorkerAsync();

            if (MainLogicWorker != null && !MainLogicWorker.IsBusy)
                MainLogicWorker.RunWorkerAsync();

            if (MainDispatcherWorker != null && !MainDispatcherWorker.IsBusy)
                MainDispatcherWorker.RunWorkerAsync();
        }

        public static void WaitForExit()
        {
            // 等待LOG输出完毕
            LogManager.WaitExitServer();

            // 等待主逻辑退出
            MainLogicThread.Instance().WaitForExit();

            // 等待主逻辑辅助线程退出
            MainDispatcherThread.Instance().WaitForExit();
        }
    }
}
